/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.model.Category;
import com.yami.shop.bean.model.CategoryBrand;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.dao.CategoryBrandMapper;
import com.yami.shop.service.CategoryBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *
 *
 * @author lgh
 * @date 2018/07/13
 */
@Service
public class CategoryBrandServiceImpl extends ServiceImpl<CategoryBrandMapper, CategoryBrand> implements CategoryBrandService {

    @Autowired
    private CategoryBrandMapper categoryBrandMapper;

    @Override
    public List<Long> getCategoryIdBrandId(Long brandId) {
        return categoryBrandMapper.getCategoryIdsByBrandId(brandId);
    }

    @Override
    public List<Category> getCategoryByBrandId(Long brandId) {
        List<Category> categoryVO = categoryBrandMapper.getCategoryByBrandId(brandId, I18nMessage.getLang());
        return categoryVO;
    }

    @Override
    public void saveByCategoryIds(Long brandId, List<Long> categoryIds) {
        if (CollUtil.isEmpty(categoryIds)) {
            return;
        }
        List<CategoryBrand> categoryBrandList = new ArrayList<>();
        categoryIds.forEach(categoryId -> {
            CategoryBrand categoryBrand = new CategoryBrand();
            categoryBrand.setBrandId(brandId);
            categoryBrand.setCategoryId(categoryId);
            categoryBrandList.add(categoryBrand);
        });
        saveBatch(categoryBrandList);
    }

    @Override
    public void updateByCategoryIds(Long brandId, List<Long> categoryIds) {
        List<Long> categoryIdDb = getCategoryIdBrandId(brandId);
        List<Long> addList = new ArrayList<>();
        categoryIds.forEach(categoryId -> {
            if (!categoryIdDb.contains(categoryId)) {
                addList.add(categoryId);
            }
        });
        saveByCategoryIds(brandId, addList);
        categoryIdDb.removeAll(categoryIds);
        if (CollUtil.isNotEmpty(categoryIdDb)) {
            categoryBrandMapper.delete(new LambdaQueryWrapper<CategoryBrand>()
                    .eq(CategoryBrand::getBrandId, brandId)
                    .in(CategoryBrand::getCategoryId, categoryIdDb)
            );
        }
    }

    @Override
    public void deleteByBrandId(Long brandId) {
        categoryBrandMapper.delete(new LambdaQueryWrapper<CategoryBrand>().eq(CategoryBrand::getBrandId, brandId));
    }
}
